package com.app.toknow.Activity;

import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;

import com.app.toknow.R;

import com.app.toknow.Adapter.SimpleSpinnerAdapter;
import com.app.toknow.Common.ConnectWSHelper;
import com.app.toknow.Common.ParseJsonUtil;
import com.app.toknow.Common.PrintAlertUtil;
import com.app.toknow.Common.WSAPIMethodName;
import com.app.toknow.View.CustomProgressDialog;
import com.app.toknow.View.ToastDialog;

import java.util.HashMap;
import java.util.Map;

public class RegisterTwoActivity extends BaseActivity implements View.OnClickListener {
    private static final String TAG = "RegisterTwoActivity";
    private ToastDialog toastDialog;
    private static final int REGISTER_STATE_SUCCESS = 0;
    private static final int REGISTER_STATE_FAIL = 1;
    private CustomProgressDialog loadingDialog = null;
    private String username;
    private String password;
    private String email;
    private TextView nav_tvTitle;
    private EditText phone;
    private EditText phoneCode;
    private Spinner spinnerPhoneArea;
    private CheckBox cbReadly;
    private Button btnRegister;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register_two);
        initNavView();
        initContentView();
        initData();
    }
    private void initNavView(){
        nav_tvTitle = (TextView)findViewById(R.id.nav_notice);
        nav_tvTitle.setText("2/2");
    }
    private void initContentView(){
        //    得到跳转到该Activity的Intent对象
        Intent intent = getIntent();
        username = intent.getStringExtra("username");
        password = intent.getStringExtra("password");
        email = intent.getStringExtra("email");
        phone = (EditText)findViewById(R.id.edittext_phone);
        phoneCode = (EditText)findViewById(R.id.edittext_phone_code);
        findViewById(R.id.register_two_rootLayout).setOnClickListener(this);
        cbReadly = (CheckBox) findViewById(R.id.cb_readly);
        btnRegister = (Button)findViewById(R.id.btn_register);
        btnRegister.setEnabled(false);
        cbReadly.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                if(((CheckBox) v).isChecked()){
                    btnRegister.setEnabled(true);
                }
                else{
                    btnRegister.setEnabled(false);
                }
            }
        });
    }
    private void initData()
    {
        spinnerPhoneArea = (Spinner) findViewById(R.id.spinner_phone_area);
        String[] strArray = this.getResources().getStringArray(R.array.array_register_phone_area);
        SimpleSpinnerAdapter simpleSpinnerAdapter = new SimpleSpinnerAdapter(getApplicationContext() ,strArray);
        spinnerPhoneArea.setAdapter(simpleSpinnerAdapter);
    }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        Log.e("main","onkeydown");
        if(keyCode==KeyEvent.KEYCODE_BACK){
            finish();
        }
        return false;
    }
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_back:
                this.finish();
                break;
            case R.id.register_two_rootLayout:
                InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
                break;
            case R.id.btn_register:
                loadingDialog = PrintAlertUtil.showProgressDialog(this, "正在注册...");
                Thread thread_login = new Thread(new Runnable() {
                    @Override
                    public void run()
                    {
                        Map<String, String> map = new HashMap<String, String>();
                        map.put("username", username);
                        Log.e("----username---",username);
                        map.put("nickname", username);
                        Log.e("----nickname---",username);
                        map.put("password", password);
                        Log.e("----password---",password);
                        RequestWS(WSAPIMethodName.REGISTER_USER, ParseJsonUtil.JsonDataType.Simple, map);
                    }
                });
                thread_login.start();
                break;
            default:
                break;
        }
    }
    /**
     * 执行异步任务
     *
     * @param params
     *            方法名+参数列表（哈希表形式）
     */
    public void RequestWS(Object... params) {
        new AsyncTask<Object, Object, String>() {
            private ParseJsonUtil.JsonDataType type;
            @Override
            protected String doInBackground(Object... params) {
                if (params != null && params.length == 3) {
                    type = (ParseJsonUtil.JsonDataType)params[1];
                    return ConnectWSHelper.GetResponse((String) params[0],
                            (Map<String, String>) params[2]);
                } else if (params != null && params.length == 2) {
                    type = (ParseJsonUtil.JsonDataType)params[1];
                    return ConnectWSHelper.GetResponse((String) params[0], null);
                } else {
                    return null;
                }
            }

            protected void onPostExecute(String result) {
                Map<String, Object> list = ParseJsonUtil.parseJSONString(result,type);
                if (result != null) {
                    Log.e("----服务器回复的信息---",list.toString());
                    Message message = new Message();
                    Bundle bundle = message.getData();
                    bundle.putInt("STATE", Integer.parseInt(list.get("STATE").toString()));
                    bundle.putString("MESSAGE", (String) list.get("MESSAGE"));
                    bundle.putInt("UserID", Integer.parseInt(list.get("UserID").toString()));
                    if(Integer.parseInt(list.get("STATE").toString()) == 1)
                        message.what = REGISTER_STATE_SUCCESS;
                    else
                        message.what = REGISTER_STATE_FAIL;
                    message.obj = "注册";
                    mHandler.sendMessage(message);
                }
                else
                {
                    Message message = new Message();
                    Bundle bundle = message.getData();
                    bundle.putString("MESSAGE", "服务器请求失败");
//                    bundle.putString("result", result);
                    message.what = REGISTER_STATE_FAIL;
                    message.obj = "服务器请求失败";
                    mHandler.sendMessage(message);
                }
            };

        }.execute(params);
    }

    private Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg)
        {
            super.handleMessage(msg);
            switch (msg.what)
            {
                case REGISTER_STATE_SUCCESS:
                    Log.e("----LOGIN---","成功");
                    //关闭对话框
                    PrintAlertUtil.dismissProgressDialog(loadingDialog);

                    GoToNextActivity();
                    break;

                case REGISTER_STATE_FAIL:
                    Log.e("----LOGIN---","失败");
                    String p = msg.getData().getString("MESSAGE");
                    PrintAlertUtil.dismissProgressDialog(loadingDialog);
                    toastDialog = ToastDialog.createToastConfig();
                    toastDialog.ToastShow(getApplicationContext(),p);
                    break;
            }
        }

    };
    void GoToNextActivity() {
        Intent intent;
        //去主页界面
        intent = new Intent(RegisterTwoActivity.this, LoginActivity.class);
        startActivity(intent);
        finish();
    }
}
